<template>
  <el-container class="wrapper">
    <el-aside class="aside" width="240px">
      <div class="filter">
        <span class="title">关键字筛选</span>
        <el-input class="search-input m-vertical" v-model.trim="keyword" placeholder="请输入内容"></el-input>
        <span class="title m-vertical">价格区间</span>
        <div class="price-label m-vertical">
          <span>最低</span>
          <span>最高</span>
        </div>
        <div class="price-select m-vertical">
          <el-input-number
              :controls="false"
              :precision="2"
              class="price-num-select"
              size="mini"
              v-model="priceMin"
              :min="0"
          ></el-input-number>
          <span>~</span>
          <el-input-number
              :controls="false"
              :precision="2"
              class="price-num-select"
              size="mini"
              v-model="priceMax"
              :max="9999"
          ></el-input-number>
        </div>
        <span class="title m-vertical">标签筛选</span>
        <div class="tags m-vertical">
          <el-check-tag
              v-for="item in tags"
              :checked="selectedTags.includes(item)"
              :key="item"
              class="tag-item"
              @change="handleTagChange(item)"
          >{{ item }}
          </el-check-tag>
        </div>
        <el-button @click="clearFilter" class="m-vertical or-btn" style="width: 100%" size="small">重设筛选</el-button>
      </div>
      <div class="cart">
        <el-popover
            placement="top"
            :show-arrow="false"
            :width="320"
            trigger="click"
        >
          <template #reference>
            <el-badge :value="cartGoodsCount">
              <el-avatar :size="48" class="or-btn-back" icon="el-icon-shopping-cart-2"></el-avatar>
            </el-badge>
          </template>

          <template #default>
            <el-container direction="vertical" class="cart-content">
              <el-scrollbar max-height="320px">
                <el-container v-if="cartGoodsCount === 0" style="justify-content: center">
                  <span style="padding: 12px 8px;font-size: 12px">购物车空空如也~快去挑选心仪的商品吧！</span>
                </el-container>

                <div class="good-preview" v-for="(good, index) in goodsInCart" :key="index">
                  <el-container style="align-items: center">
                    <img :src="good.img" alt="good">
                    <el-container direction="vertical" style="justify-content: space-between; margin-left: 4px">
                      <span style="font-size: 12px; max-width: 160px">{{ good.name }}</span>
                      <span style="color: #eea2a4">￥{{ good.price.toFixed(2) }}</span>
                    </el-container>
                  </el-container>
                  <el-container style="justify-content: space-between; align-items: center; padding: 0 16px">
                    <span style="cursor: pointer; color: #eea2a4" @click="cartRemove(good)"
                          class="el-icon-minus"></span>
                    <span>{{ good.count }}</span>
                    <span style="cursor: pointer; color: #eea2a4" @click="cartAdd(good)" class="el-icon-plus"></span>
                  </el-container>
                </div>
              </el-scrollbar>
              <el-container style="justify-content: space-between; margin-top: 12px">
                <el-container>
                  <el-popconfirm
                      title="确定要清空购物车吗？"
                      confirm-button-text="确定"
                      cancel-button-text="取消"
                      @confirm="cartRemoveAll"
                  >
                    <template #reference>
                      <el-button
                          v-show="cartGoodsCount > 0"
                          type="text"
                          style="color: #eea2a4;font-size: 12px"
                      >清空购物车
                      </el-button>
                    </template>
                  </el-popconfirm>
                </el-container>
                <el-container style="align-items: center;justify-content: flex-end">
                  <span style="color: #eea2a4;font-size: 12px;">￥</span>
                  <span style="color: #eea2a4;font-size: 20px;">{{ cartPrice.toFixed(2) }}</span>
                </el-container>
              </el-container>
            </el-container>
          </template>
        </el-popover>

        <el-popover
            placement="top"
            :width="120"
            trigger="click"
        >
          <template #reference>
            <div>
              <el-button
                  icon="el-icon-check"
                  class="or-btn-back"
                  size="small"
                  v-if="cartGoodsCount > 0"
              >立即购买 ￥{{ cartPrice.toFixed(2) }}
              </el-button>
            </div>
          </template>

          <template #default>
            <img :src="qrCode" alt="qrCode" style="width: 100%">
          </template>
        </el-popover>
      </div>
    </el-aside>

    <el-scrollbar
        height="calc(100vh - 144px)"
        style="width: 100%"
    >
      <water-fall
          gap="10px"
          width="240px"
          class="container"
          :data="goods"
          :delay="true"
          v-infinite-scroll="fetchGoods"
          :infinite-scroll-immediate="false"
          :infinite-scroll-delay="1000"
      >
        <template #default="good">
          <NecessityGoodCard class="good" :class="filtered(good.key) ? '' : 'unfocused'"
                             :good="good"></NecessityGoodCard>
        </template>
      </water-fall>
      <div class="loading">
        <span>正在加载...</span>
      </div>
    </el-scrollbar>
  </el-container>
</template>

<script>
import WaterFall from 'kuan-vue-waterfall'
import NecessityGoodCard from '../../components/necessity/NecessityGoodCard';
import Resources from '../../resources';
import {imageSync} from 'qr-image';

const Goods = Resources.Goods;
export default {
  name: 'NecessityGood',
  components: {NecessityGoodCard, WaterFall},
  data: () => ({
    goods: [],
    keyword: '',
    priceMin: 0,
    priceMax: 999,
    tags: ['猫粮', '猫砂', '罐头', '猫窝', '猫条', '猫笼', '猫碗', '药品', '卫生'],
    selectedTags: [],
  }),
  methods: {
    async fetchGoods(count = 12) {
      let goodCount = this.goods.length;
      const loadGoods = [...Array(count).keys()].map(() => ({key: `${goodCount++}`, ...Goods.random()}));
      this.goods = [...this.goods, ...loadGoods];
    },
    filtered(key) {
      let good = this.goods.find((good) => good.key === key);

      let keyword = !this.keyword || good.name.includes(this.keyword);
      let priceMin = !this.priceMin || good.price >= this.priceMin;
      let priceMax = !this.priceMax || good.price <= this.priceMax;
      let tag = this.selectedTags.length === 0 || good.tags.some((t) => this.selectedTags.includes(t));

      return keyword && priceMin && priceMax && tag;
    },
    handleTagChange(item) {
      if (this.selectedTags.includes(item)) {
        this.selectedTags.splice(this.selectedTags.findIndex((x) => x === item), 1);
      } else {
        this.selectedTags.push(item);
      }
    },
    clearFilter() {
      this.priceMin = 0;
      this.priceMax = 200;
      this.keyword = '';
      this.selectedTags = [];
    },
    cartAdd(good) {
      this.$store.commit('addNecessityGoodToCart', good);
    },
    cartRemove(good) {
      this.$store.commit('removeNecessityGoodFromCart', good);
    },
    cartRemoveAll() {
      this.$store.commit('removeAllNecessityGoodFromCart');
    }
  },
  computed: {
    goodsInCart() {
      return this.$store.state.necessityGoodsInCart;
    },
    cartGoodsCount() {
      if (this.$store.state.necessityGoodsInCart.length > 0)
        return this.$store.state.necessityGoodsInCart.map((x) => x.count).reduce((p, c) => p + c);
      else return 0;
    },
    cartPrice() {
      if (this.$store.state.necessityGoodsInCart.length > 0)
        return this.$store.state.necessityGoodsInCart.map((x) => x.count * x.price).reduce((p, c) => p + c);
      else return 0;
    },
    qrCode() {
      let binary = '';
      imageSync(`You have paid ￥${this.cartPrice} for your cat! Hope you a nice day with your dearest!`).forEach((i) => binary += String.fromCharCode(i));
      return 'data:image/png;base64,' + btoa(binary);
    }
  },
  mounted() {
    this.fetchGoods(24);
  },
}
</script>

<style lang="less" scoped>
@import "../../assets/less/common";

.aside {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 20px 16px;

  .m-vertical {
    margin: 12px 0;
  }

  .price-label {
    display: flex;
    justify-content: space-around;
    font-size: 12px;
    margin-bottom: 0;
  }

  /deep/ .el-input__inner:focus {
    border-color: @theme-color;
  }

  .price-select {
    display: flex;
    justify-content: space-around;
    align-items: center;
    margin-top: 0;

    /deep/ .el-input-number__decrease:hover, /deep/ .el-input-number__increase:hover {
      color: @theme-color;
    }
  }

  .tags {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;

    .tag-item {
      margin: 2px 0;
    }
  }

  /deep/ .el-badge__content {
    margin-top: 4px;
    margin-right: 4px;
  }
}

/deep/ .or-btn-back:focus {
  background-color: @theme-color;
  border-color: @theme-color;
  color: white;
}

.or-btn {
  &:hover, &:focus {
    border-color: #F9C3C5;
    color: @theme-color;
    background-color: #FDF5F5;
  }
}

.or-btn-back {
  color: white;
  cursor: pointer;
  background-color: @theme-color;
  border-color: @theme-color;

  &:hover {
    color: white;
    border-color: #F9C3C5;
    background-color: #F9C3C5;
  }
}

/deep/ .water-fall-more {
  display: none !important;
}

.good-preview {
  display: flex;
  flex-direction: row;
  align-items: center;
  padding: 1px 0;
  border-bottom: 1px solid #F9C3C5;

  img {
    width: 64px;
  }
}

.el-check-tag.is-checked {
  color: @theme-color;
  background-color: #F5F7FA;
}

.container {
  width: 100%;
  height: 100%;
}

.loading {
  display: flex;
  justify-content: center;
  font-size: 12px;
  color: gray;
}

.wrapper {
  justify-content: center;
}

.unfocused {
  opacity: .1;
  transition: opacity .5s;
}

.title {
  border-left: 8px solid @theme-color;
  padding-left: 8px;
}

.cart {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-input {
  border-radius: 0;

  &:focus {
    border-color: @theme-color;
  }
}
</style>
